<?php
require_once 'Surveys.php';
require_once 'SurveysCompleted.php';
require_once '../application/modules/loan/models/Loans.php';

class Survey_SurveyController extends HTech_Controller_Action
{
    function init()
    {
        $cfg = array(
            'model' => 'Surveys', 
            'form' => 'Emms_Form_Survey_ApplySurvey',
            'layout' => array('view' => 'survey'),
            'config' => array('add' => 'surveys'),
            'flashMessenger' => true,
            'actionContext' => array(
                'export' => array('xml','csv'))
        );
        parent::init($cfg);
    }    
    
    public function applyAction()
    {       
        $loans = new Loans();
        $this->view->loan = $loans->find((int) $this->_request->getParam('loan'))->current(); 
        
        if (!$this->view->loan) {
            $this->_helper->flashMessenger->addMessage($this->view->translate('Invalid survey application request'));
            $this->redirect('/default/auth/deny'); 
        }
        $this->view->form = new $this->_cfg['form']($this->view->loan);
        
        if ($this->getRequest()->isPost()) {
            if ($this->view->form->isValid($this->getRequest()->getPost())) {
                $data = $this->view->form->getValues();
                $surveyCompleted = new SurveysCompleted(array('name' => 'surveys_completed'));
                foreach($data as $questionId => $answerId) {
                    if(is_int($questionId)) {
                        $select = $surveyCompleted->select();
                        $select->where('SurveyId = ?', $data['SurveyId']);
                        $select->where('QuestionId = ?', $questionId);
                        $select->where('ClientId = ?', $data['ClientId']);
                        $cycle = $surveyCompleted->fetchAll($select)->count() + 1;
                        
                        $surveyCompleted->insert(array(
                            'SurveyId' => $data['SurveyId'],
                            'QuestionId' => $questionId,
                            'AnswerId' => $answerId,
                            'ClientId' => $data['ClientId'],
                            'OfficerUserId' => $data['OfficerUserId'],
                            'LoanId' => $data['LoanId'],
                            'Date' => $data['Date'],
                            'Cycle' => $cycle
                        ));
                    }
                } 
                $this->redirect(sprintf('/loan/application/view/id/%s',$this->view->loan->LoanMasterId)); 
            }
        }
        $this->_helper->layout->setLayout('survey');
    }
}
